package com.fanketly.lib_dialog

import android.hardware.fingerprint.FingerprintManager
import android.os.Bundle
import android.os.CancellationSignal
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.annotation.Nullable
import androidx.fragment.app.DialogFragment
import javax.crypto.Cipher


/**
 *Create by Fanketly on 2022/7/10
 *Gitee:https://gitee.com/fanketly
 *desc:
 */
class FingerprintDialogFragment(private val onSuccess: () -> Unit) : DialogFragment() {
    //    private lateinit var fingerprintManager: BiometricPrompt
    private var mFingerprintManager: FingerprintManager? = null
    private var mCancellationSignal: CancellationSignal? = null
    private var isSelfCancelled: Boolean = true
    var cipher: Cipher? = null
    private var errorMsg: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (context == null) {
            // TODO: 弹窗提示
            dismiss()
        }
        mFingerprintManager = requireContext().getSystemService(FingerprintManager::class.java)
        setStyle(STYLE_NORMAL, android.R.style.Theme_Material_Light_Dialog)
    }

    @Nullable
    override fun onCreateView(
        inflater: LayoutInflater,
        @Nullable container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        val v: View = inflater.inflate(R.layout.core_dialog_fingerptint_dialog, container, false)
        errorMsg = v.findViewById(R.id.tv_content)
        val cancel = v.findViewById<TextView>(R.id.tv_top)
        cancel.setOnClickListener {
            dismiss()
            stopListening()
        }
        return v
    }

    override fun onResume() {
        super.onResume()
        startListening(cipher!!)
    }

    override fun onPause() {
        super.onPause()
        stopListening()
    }

    private fun startListening(cipher: Cipher) {
        isSelfCancelled = false
        mCancellationSignal = CancellationSignal()
        mFingerprintManager?.authenticate(
            FingerprintManager.CryptoObject(cipher),
            mCancellationSignal,
            0,
            object : FingerprintManager.AuthenticationCallback() {
                override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
                    if (!isSelfCancelled) {
                        errorMsg!!.text = errString
                        if (errorCode == FingerprintManager.FINGERPRINT_ERROR_LOCKOUT) {
//                            Toast.makeText(mActivity, errString, Toast.LENGTH_SHORT).show()
                            dismiss()
                        }
                    }
                }

                override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence) {
                    errorMsg!!.text = helpString
                }

                override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) {
//                    Toast.makeText(mActivity, "指纹认证成功", Toast.LENGTH_SHORT).show()
//                    mActivity.onAuthenticated()
                    onSuccess.invoke()
                }

                override fun onAuthenticationFailed() {
                    errorMsg!!.text = "指纹认证失败，请再试一次"
                }
            },
            null
        )
    }

    private fun stopListening() {
        if (mCancellationSignal != null) {
            mCancellationSignal!!.cancel()
            mCancellationSignal = null
            isSelfCancelled = true
        }
    }


}